% Calculates log-likelihood function value for mixed logit model
% Written by Kenneth Train, July 27, 2006, revised July 31, 2006
% Last modified by Heather Snell, Dec 18, 2020

%
% This code is input to Matlab's funcmin command
%
% Input param is a column vector of parameters, dimension (NF+NV+NV)x1
%     containing the fixed coefficients, the first parameters of the random
%     coefficients, and then the second parameters of the random coefficients
% Output ll is the scalar value of the negative of the simulated log-likelihood 
%     at the input parameters

function [ll] = logliknog(param) %this loglik function does not have gradient coded

global NV NF IDV WANTWGT WGT NAMES NAMESF modelname printest ANA

%restructure the parameters
[f, b, w]=getbetas(param);

%get probabilities--most of the work is in the functions 
%llgrad2nog and dodiscountingnog (nog means no gradient coded)
[p]=llgrad2nog(f,b,w); 

if WANTWGT == 0
    ll=-sum(log(p),2);

else
    ll=-sum(WGT.*log(p),2);

end

%if NV>0 & sum(IDV(:,2)==5) >0   %Zero mean error components
%   z=[ones(NF,1) ; IDV(:,2) ~= 5 ; ones(NV,1)];
%end
disp('----------------------------------------')
disp(datetime);
disp('LL');
disp(-ll);


 if printest==1 %% if you want to see the estimate at each step, use printest=1
    disp('RANDOM COEFFICIENTS');

    disp(' ');
    disp('                B Est     W Est');
    disp('               ------------------');
    disp('                  ');
    for r=1:length(NAMES)
        fprintf('%-11s %10.4f %10.4f %10.4f %10.4f\n', NAMES{r,1}, [b(r,1) w(r,1)]);
        disp(' ');  
    end

    if(NF>0)
        disp('FIXED COEFFICIENTS');

        disp(' ');
        disp('                F Est');
        disp('               ------------');
        disp('                  ');
        for r=1:length(NAMESF)
            fprintf('%-11s %10.4f %10.4f %10.4f %10.4f\n', NAMESF{r,1}, f(r,1));
            disp(' ');
        end
    end
 end

disp('LL');
disp(-ll);
 
disp('----------------------------------------')
save(modelname); %workspace is saved every iteration in case an issue arises 
                 %and estimation is not complete before stopping (e.g. accidental computer shut
                 %down or iteration limit is met).
end
